package com.binarysoft.service.id;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collection;

import com.binarysoft.service.common.multiconnpool.MultipleConnectionPoolService;

import common.framework.dsb.client.DefaultServiceFactory;
import common.framework.dsb.client.ServiceFactory;
import common.framework.log.Logger;

public class IDMysqlDAO implements IDDAO {

	@Override
	public Collection<Long> nextIDs(int numberOfIDs) throws Exception {
		ServiceFactory serviceFactory = new DefaultServiceFactory();
		MultipleConnectionPoolService connectionPoolService = serviceFactory.lookup("DSB/MultipleConnectionPoolService");
		String sql = "call sp_id_generator(?,?,?)";
		Connection connection = connectionPoolService.getConnection(DSB_SERVER_POOL_NAME);
		Collection<Long> result = new ArrayList<Long>();
		try {

			CallableStatement cstatement = connection.prepareCall(sql);
			cstatement.setInt(1, numberOfIDs);
			cstatement.registerOutParameter(2, Types.INTEGER);
			cstatement.registerOutParameter(3, Types.INTEGER);
			Logger.log(Logger.LOW_LEVEL, "begin call procedure");
			cstatement.execute();
			long beginid = cstatement.getLong(2);
			long endid = cstatement.getLong(3);
			cstatement.close();
			do {
				result.add(beginid);
				beginid++;
			} while (beginid <= endid);
		} finally {
			if (connection != null) {
				connection.close();
			}
		}
		return result;
	}
}
